package com.fh.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fh.common.exception.Assert;
import com.fh.common.web.impl.AbstractServiceImpl;
import com.fh.modules.oms.OrderStatus;
import com.fh.modules.oms.entity.OmsOrderReturn;
import com.fh.modules.oms.entity.OmsOrderReturnItem;
import com.fh.modules.oms.entity.OmsOrderWechat;
import com.fh.modules.oms.entity.OmsOrderWechatItem;
import com.fh.modules.oms.feign.FhWechatOrderApi;
import com.fh.modules.oms.mapper.OmsOrderReturnMapper;
import com.fh.modules.oms.service.IOmsOrderReturnItemService;
import com.fh.modules.oms.service.IOmsOrderReturnService;
import com.fh.modules.oms.service.IOmsOrderWechatItemService;
import com.fh.modules.oms.service.IOmsOrderWechatService;
import com.fh.modules.ums.entity.UmsMember;
import com.fh.modules.ums.entity.UmsMemberPartnerInfo;
import com.fh.modules.ums.model.MemberModel;
import com.fh.modules.ums.model.PartnerModel;
import com.fh.modules.ums.service.IUmsMemberService;
import com.fhMall.request.OrderReturnApplyRequest;
import com.fhMall.request.OrderReturnHandleRequest;
import com.fhMall.request.WechatOrderReturnHandleResquest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 订单退货
 * @author： code generator
 * @date：   2019-10-18
 * @version： V1.0
 */
@Service
public class OmsOrderReturnServiceImpl extends AbstractServiceImpl<OmsOrderReturnMapper, OmsOrderReturn> implements IOmsOrderReturnService {

    @Autowired
    private IOmsOrderWechatService omsOrderWechatService;

    @Autowired
    private IOmsOrderWechatItemService omsOrderWechatItemService;

    @Autowired
    private IOmsOrderReturnItemService omsOrderReturnItemService;

//    @Autowired
//    private FhWechatOrderApi fhWechatOrderApi;

    @Autowired
    private IUmsMemberService umsMemberService;

    @Override
    @Transactional
    public void applyOrderReturn(OrderReturnApplyRequest orderReturnApplyRequest) {
        OmsOrderWechat omsOrderWechat=omsOrderWechatService.getById(orderReturnApplyRequest.getOrderId());
        Assert.isTrue(omsOrderWechat==null,"订单不存在");
        omsOrderWechatService.changeOrderStatus(omsOrderWechat, OrderStatus.REFUNDING);
        //新增销售退货单，同事新增销售退货商品行
        this.addOrderReturn(orderReturnApplyRequest,omsOrderWechat);
    }

    @Override
    @Transactional
    public WechatOrderReturnHandleResquest handleOrderReturn(OrderReturnHandleRequest orderReturnHandleRequest) {

        OmsOrderReturn omsOrderReturn = super.getById(orderReturnHandleRequest.getOrderReturnId());
        omsOrderReturn.setStatus(orderReturnHandleRequest.getStatus() == 1 ? 1 : 3);
        omsOrderReturn.setHandleNote(orderReturnHandleRequest.getHandleNote());
        omsOrderReturn.setHandleTime(new Date());
        omsOrderReturn.setHandleMan(orderReturnHandleRequest.getHandleMan());
        super.updateById(omsOrderReturn);

        OmsOrderWechat omsOrderWechat = omsOrderWechatService.getById(omsOrderReturn.getOrderId());
        WechatOrderReturnHandleResquest wechatOrderReturnHandleResquest = WechatOrderReturnHandleResquest.builder()
                .orderReturnId(omsOrderReturn.getId())
                .orderId(omsOrderReturn.getOrderId())
                .payPrice(omsOrderReturn.getApplyPrice())
                .wechatPrepayId(omsOrderWechat.getWechatPrepayId())
                .payOrderPrice(omsOrderWechat.getPayPrice())
                .transactionId(omsOrderWechat.getTransactionId())
                .build();
        if (Objects.equals(orderReturnHandleRequest.getStatus(), 1)){
//            String result = fhWechatOrderApi.orderReturnHandle(wechatOrderReturnHandleResquest);
//            System.out.println("refund result "+result);
        }
        return wechatOrderReturnHandleResquest;

    }

    @Override
    public void returnSuccess(String outRefundNo, String outTradeNo, String transactionId) {
        LambdaQueryWrapper<OmsOrderWechat> orderWechatLambdaQueryWrapper = new LambdaQueryWrapper<OmsOrderWechat>();
        orderWechatLambdaQueryWrapper.eq(OmsOrderWechat::getWechatPrepayId, outTradeNo)
                .eq(OmsOrderWechat::getTransactionId, transactionId);

        OmsOrderWechat omsOrderWechat = omsOrderWechatService.getOne(orderWechatLambdaQueryWrapper);
        Assert.isTrue(omsOrderWechat == null,outTradeNo + "订单不存在");

        LambdaQueryWrapper<OmsOrderReturn> omsOrderReturnLambdaQueryWrapper = new LambdaQueryWrapper<OmsOrderReturn>();
        omsOrderReturnLambdaQueryWrapper.eq(OmsOrderReturn::getOrderId, omsOrderWechat.getId())
                .eq(OmsOrderReturn::getId, outRefundNo);

        OmsOrderReturn omsOrderReturn = super.getOne(omsOrderReturnLambdaQueryWrapper);
        Assert.isTrue(omsOrderReturn == null,omsOrderWechat.getId() + "退款单不存在");
        omsOrderReturn.setStatus(2);

        omsOrderWechatService.changeOrderStatus(omsOrderWechat, OrderStatus.REFUNDED);
        super.updateById(omsOrderReturn);
    }

    /**
     *  退款后续处理扣减 用户的积分，购买金额  以及扣减合伙人积分和提成等
     * @param
     * @param
     */
    private void refundProcessing(OmsOrderWechat omsOrderWechat, OmsOrderReturn omsOrderReturn){
        MemberModel memberModel = umsMemberService.getMemberInfo(omsOrderWechat.getMemberId());
        UmsMember memberInfo = memberModel.getMemberInfo();
        PartnerModel partnerInfo = memberModel.getPartnerInfo();
        //积分,实际支付价格-运费
        BigDecimal payPrice = omsOrderWechat.getPayPrice();
        BigDecimal productMoney = payPrice.subtract(omsOrderWechat.getFreightPrice());
        // TODO 退款 处理 积分 等
        if (Objects.equals(memberInfo.getPartnerType(), 1)){
            //合伙人
            umsMemberService.addMemberConsumptionInformation(0, payPrice.negate(), memberInfo);
            UmsMemberPartnerInfo umsMemberPartnerInfo = umsMemberService.getPartnerInfo(omsOrderWechat.getMemberId());
          // umsMemberService.addParnterTeamSale(this.calculateTeamCommission(omsOrderWechat, umsMemberPartnerInfo), productMoney, umsMemberPartnerInfo);
        }else {
            //非合伙人
            umsMemberService.addMemberConsumptionInformation(productMoney.negate().intValue(), payPrice.negate(), memberInfo);
            if(partnerInfo != null && partnerInfo.getOwnPartnerInfo() != null){
                UmsMemberPartnerInfo umsMemberPartnerInfo = partnerInfo.getOwnPartnerInfo();
            //    umsMemberService.addParnterTeamSale(this.calculateTeamCommission(omsOrderWechat, umsMemberPartnerInfo), productMoney, umsMemberPartnerInfo);
            }
        }
    }

    /**
     *  新增销售退货单，同事新增销售退货商品行
     * @param orderReturnApplyRequest
     * @param omsOrderWechat
     */
    private void addOrderReturn(OrderReturnApplyRequest orderReturnApplyRequest, OmsOrderWechat omsOrderWechat){
        OmsOrderReturn omsOrderReturn=new OmsOrderReturn();
        omsOrderReturn.setOrderId(orderReturnApplyRequest.getOrderId());
        omsOrderReturn.setReason(orderReturnApplyRequest.getReason());
        omsOrderReturn.setDescription(orderReturnApplyRequest.getDescription());
        omsOrderReturn.setMemberId(orderReturnApplyRequest.getMemberId());
        omsOrderReturn.setApplyPrice(omsOrderWechat.getPayPrice());
        omsOrderReturn.setReturnPrice(omsOrderWechat.getPayPrice().subtract(omsOrderWechat.getFreightPrice()));
        omsOrderReturn.setProductTypeCount(omsOrderWechat.getItemCount());
        omsOrderReturn.setReceiver(omsOrderWechat.getReceiverName());
        omsOrderReturn.setReceiverPhone(omsOrderWechat.getReceiverPhone());
        omsOrderReturn.setReceiverAddress(omsOrderWechat.getReceiverDetailAddress());
        omsOrderReturn.setReceiveTime(omsOrderWechat.getReceiveTime());
        omsOrderReturn.setStatus(0);
        this.save(omsOrderReturn);
    }

    /**
     * 增加销售退货行
     * @param orderId
     * @param orderReturnId
     * @param memberId
     */
    private void addOrderReturnItem(Integer orderId,Integer orderReturnId,Integer memberId){
        LambdaQueryWrapper<OmsOrderWechatItem> query = new LambdaQueryWrapper<OmsOrderWechatItem>();
        query.eq(OmsOrderWechatItem::getOrderId,orderId);
        List<OmsOrderWechatItem> orderItem=omsOrderWechatItemService.list(query);
        for (OmsOrderWechatItem omsOrderWechatItem : orderItem) {
            OmsOrderReturnItem omsOrderReturnItem=new OmsOrderReturnItem();
            omsOrderReturnItem.setMemberId(memberId);
            omsOrderReturnItem.setOrderItemId(omsOrderWechatItem.getId());
            omsOrderReturnItem.setOrderReturnId(orderReturnId);
            omsOrderReturnItem.setStatus(0);
            omsOrderReturnItem.setReturnPrice(omsOrderWechatItem.getProductPrice());
            omsOrderReturnItem.setProductCount(omsOrderWechatItem.getProductQuantity());
            omsOrderReturnItemService.save(omsOrderReturnItem);
        }

    }
}
